package com.rent.member.config;


import com.security.config.IgnoreUrlsConfig;
import com.security.handle.RestAuthenticationEntryPointHandle;
import com.security.handle.RestfulAccessDeniedHandler;
import com.security.intercept.DynamicSecurityFilter;
import com.security.intercept.JwtAuthenticationTokenFilter;
import com.security.service.IDynamicSecurityService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.util.CollectionUtils;

import java.util.Arrays;
import java.util.Map;


/**
 * SpringSecurity 5.4.x以上新用法配置，仅用于配置HttpSecurity
 * Created by zn on 2019/11/5.
 */
@Slf4j
@EnableWebSecurity
@Configuration
@EnableGlobalMethodSecurity(securedEnabled = true)
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private IgnoreUrlsConfig ignoreUrlsConfig;

    @Autowired
    private RestfulAccessDeniedHandler restfulAccessDeniedHandler;

    @Autowired
    private RestAuthenticationEntryPointHandle restAuthenticationEntryPoint;


    @Autowired(required = false)
    private IDynamicSecurityService dynamicSecurityService;


    @Autowired(required = false)
    private DynamicSecurityFilter dynamicSecurityFilter;

    @Autowired
    private JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;


    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        log.info("认证拦截....");
        ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry registry = httpSecurity
                .authorizeRequests();
        //不需要保护的资源路径允许访问
        int l = ignoreUrlsConfig.getUrls().size();
        String[] urls = ignoreUrlsConfig.getUrls().toArray(new String[l]);
        log.info("白名单:{}", Arrays.toString(urls));
        registry.antMatchers(urls).permitAll();
        //允许跨域请求的OPTIONS请求
        registry.antMatchers(HttpMethod.OPTIONS)
                .permitAll();
        //有动态权限配置时添加动态权限校验过滤器
        if (dynamicSecurityService != null) {
            Map<String, ConfigAttribute> resourceMap = dynamicSecurityService.loadDataSource();
            if (!CollectionUtils.isEmpty(resourceMap)) {
                log.info("添加动态权限拦截");
                registry.and().addFilterBefore(dynamicSecurityFilter, FilterSecurityInterceptor.class);
            }
        }
        // 任何请求需要身份认证
        registry.and()
                .authorizeRequests()
                .anyRequest()
                .authenticated()
                // 关闭跨站请求防护及不使用session
                .and()
                .csrf()
                .disable()
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                // 自定义权限拒绝处理类
                .and()
                .exceptionHandling()
                .accessDeniedHandler(restfulAccessDeniedHandler)
                .authenticationEntryPoint(restAuthenticationEntryPoint)
                // 自定义权限拦截器JWT过滤器
                .and()
                .addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
    }

}
